<template>
  <div class="join-addEdit">
    <el-dialog :append-to-body="true" :title="title" v-model="show" @close="cancelFun" destroy-on-close>
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="关键字:" prop="key">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.key" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="提示原因:" prop="context">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.context" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelFun" size="large">取消</el-button>
          <el-button type="primary" @click="confirmFun" size="large">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { computed, ref, watch, defineEmits, reactive } from 'vue'
import {
  addAddressKey,
  editAddressKey,
} from '@api/addressKey'
import { ElMessage } from 'element-plus'

const props = defineProps({
  status: {
    type: String,
    default: null
  },
  show: {
    type: Boolean,
    default: null
  },
  addEditData: {
    type: Object,
    default: {
      id: '',
      key: '',
      context: ''
    }
  }
})

const formRef = ref()

const form = ref({
  id: '',
  key: '',
  context: ''
})

const rules = reactive({
  key: [{ required: true, message: '关键字不能为空!', trigger: 'blur' }],
  context: [{ required: true, message: '提示原因不能为空!', trigger: 'blur' }]
})

const emit = defineEmits(['hide-addEdit'])

const title = computed(() => {
  return props.status == 'add' ? '添加地址黑名单' : '编辑地址黑名单'
})

function confirmFun() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = '';
      let {
        id,
        key,
        context
      } = form.value;

      if (props.status == 'add') {
        res = await addAddressKey({
          key,
          context
        })
      } else if (props.status == 'edit') {
        res = await editAddressKey({
          id,
          key,
          context
        })
      }

      if (res.code == 200) {
        ElMessage({
          message: '操作成功!',
          type: 'success',
        })
        emit('hide-addEdit', props.status)
      }

    }
  })
}

function cancelFun() {
  emit('hide-addEdit', 'cancel')
}

// 省市区
const handleChange = (value) => {
  // form.value.shengshiqu = value ? [CodeToText[value[0]], CodeToText[value[1]], CodeToText[value[2]]] : []
}

watch(
  () => props.addEditData,
  (newValue, oldValue) => {
    form.value.id = newValue.id
    form.value.key = newValue.key
    form.value.context = newValue.context
  },
  { deep: true }
)
</script>
<style lang="scss" scoped></style>
